package com.zzwx.controller.sys;

import com.zzwx.dao.entity.sys.Menu;
import com.zzwx.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("zzwxIndex")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value="toLogin",method = RequestMethod.GET)
    public String toLogin(){
        return "zzwxLogin";
    }

    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(String userName, String password, Model model){

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
        try{
            subject.login(token);
            return "redirect:/index";
        }catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("userName",userName);
            model.addAttribute("errorMsg",e.getMessage());
            return "zzwxLogin";
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            model.addAttribute("userName",userName);
            model.addAttribute("errorMsg",e.getMessage());
            return "zzwxLogin";
        }catch (LockedAccountException e){
            e.printStackTrace();
            model.addAttribute("userName",userName);
            model.addAttribute("errorMsg",e.getMessage());
            return "zzwxLogin";
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("userName",userName);
            model.addAttribute("errorMsg","服务器异常");
            return "zzwxLogin";
        }
    }

    @RequestMapping(value = "findMenus/{menuId}",method = RequestMethod.GET)
    @ResponseBody
    public Menu findMenuById(@PathVariable("menuId") int menuId){
        return userService.findMenuById(menuId);
    }
}
